﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.OleDb;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Net;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using accessSyncTools;
using Microsoft.Win32.SafeHandles;
using Newtonsoft.Json;
using Spire.Xls;

namespace chengz
{
    public partial class form1 : Form
    {
        [DllImport("kernel32.dll", SetLastError = true)]
        private static extern IntPtr CreateFile(
            string lpFileName,
            uint dwDesiredAccess,
            uint dwShareMode,
            uint lpSecurityAttributes,
            uint dwCreationDisposition,
            uint dwFlagsAndAttributes,
            uint hTemplateFile);

        private const uint GENERIC_WRITE = 0x40000000;
        private const uint FILE_SHARE_WRITE = 0x2;
        private const uint OPEN_EXISTING = 0x3;
        
        [DllImport("kernel32")]
        static extern bool AllocConsole();

        Configuration config;
        OleDbConnection conn;

        string serverUrl = "";

        string httpPost(string url, string json)
        {
            //textBox1.Text += url + "\r\n";
            byte[] bs = Encoding.UTF8.GetBytes(json);

            HttpWebRequest httpWebRequest = WebRequest.Create(url) as HttpWebRequest;

            httpWebRequest.Method = "POST";
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.ContentLength = bs.Length;

            try
            {
                using (Stream reqStream = httpWebRequest.GetRequestStream())
                {
                    reqStream.Write(bs, 0, bs.Length);
                }

                using (WebResponse wr = httpWebRequest.GetResponse())
                {
                    using (var responseStream = wr.GetResponseStream())
                    {
                        byte[] readBuffer = new byte[1000];
                        List<byte> allData = new List<byte>();
                        int readBytes;

                        do
                        {
                            readBytes = responseStream.Read(readBuffer, 0, readBuffer.Length);

                            for (var i = 0; i < readBytes; i++)
                            {
                                allData.Add(readBuffer[i]);
                            }

                        } while (readBytes > 0);//如果readBytes为0表示HttpWebResponse中的所有数据已经被读取完毕

                        string message = Encoding.UTF8.GetString(allData.ToArray());
                        //textBox1.Text += message + "\r\n\r\n";
                        //worker.ReportProgress(99, message + "\r\n");
                        return message + "\r\n\r\n";

                    }
                }

            }
            catch (Exception error)
            {
                //MessageBox.Show(error.Message);
                //worker.ReportProgress(50, "异常, " + error.Message + "\r\n");
                //textBox1.Text += "异常, " + error.Message + "\r\n";
                return "异常, " + error.Message + " 请检查网络！\r\n";

            }
        }

        string httpGet(string url)
        {
            Console.WriteLine(url);

            HttpWebRequest httpWebRequest = WebRequest.Create(url) as HttpWebRequest;
            httpWebRequest.Method = "GET";

            try
            {
                using (WebResponse wr = httpWebRequest.GetResponse())
                {
                    using (var responseStream = wr.GetResponseStream())
                    {
                        byte[] readBuffer = new byte[1000];
                        List<byte> allData = new List<byte>();
                        int readBytes;

                        do
                        {
                            readBytes = responseStream.Read(readBuffer, 0, readBuffer.Length);

                            for (var i = 0; i < readBytes; i++)
                            {
                                allData.Add(readBuffer[i]);
                            }

                        } while (readBytes > 0);//如果readBytes为0表示HttpWebResponse中的所有数据已经被读取完毕

                        string message = Encoding.UTF8.GetString(allData.ToArray());
                        //textBox1.Text += message + "\r\n\r\n";
                        //worker.ReportProgress(99, message + "\r\n");
                        return message + "\r\n\r\n";

                    }
                }

            }
            catch (Exception error)
            {
                //MessageBox.Show(error.Message);
                //worker.ReportProgress(50, "异常, " + error.Message + "\r\n");
                //textBox1.Text += "异常, " + error.Message + "\r\n";
                return "异常, " + error.Message + " 请检查网络！\r\n";

            }
        }

        public form1(string chengzy)
        {
            InitializeComponent();
            textBox_chengzy.Text = chengzy;
        }

        void replaceTemplate(Worksheet sheet, string zhanwf, string val)
        {
            CellRange[] ranges = sheet.FindAllString(zhanwf, false, false);
            foreach (CellRange cellRange in ranges)
            {
                cellRange.Text = val;
                cellRange.Style.WrapText = true;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Workbook workbook = new Workbook();
            workbook.LoadFromFile(Environment.CurrentDirectory + @"\template.xlsx");

            Worksheet sheet = workbook.Worksheets[0];

            replaceTemplate(sheet, "{{wulgs}}", comboBox_wulgs.Text);
            replaceTemplate(sheet, "{{wul}}", comboBox_wul.Text);
            replaceTemplate(sheet, "{{guig}}", comboBox_guig.Text);
            replaceTemplate(sheet, "{{yunsgs}}", comboBox_yunsgs.Text);
            replaceTemplate(sheet, "{{chepNu}}", comboBox_chepNu.Text);

            if (comboBox_czfs.Text.Equals("手动"))
                replaceTemplate(sheet, "{{createTime}}", textBox_czsj.Text);
            else
            {
                if (budczd != null && budczd.Equals("1"))
                {
                    replaceTemplate(sheet, "{{createTime}}", textBox_czsj.Text);

                } else {
                    textBox_czsj.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    replaceTemplate(sheet, "{{createTime}}", textBox_czsj.Text);
                }
                
            }

            replaceTemplate(sheet, "{{maoz}}", textBox_maoz.Text);
            replaceTemplate(sheet, "{{piz}}", textBox_piz.Text);
            replaceTemplate(sheet, "{{jingz}}", textBox_jingz.Text);
            replaceTemplate(sheet, "{{remark}}", textBox_remark.Text);
            replaceTemplate(sheet, "{{chengzbh}}", g_czbh);
            replaceTemplate(sheet, "{{chengzy}}", textBox_chengzy.Text);
            replaceTemplate(sheet, "{{chengzfs}}", comboBox_czfs.Text);
            
            workbook.SaveToFile(Environment.CurrentDirectory + @"\过磅单.xlsx");

            // 利用excel的缩放
            Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel.Workbook wb = excelApp.Workbooks.Open(Environment.CurrentDirectory + @"\过磅单.xlsx");
            Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets[1];

            try
            {
                ws.PrintOutEx(Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            }
            catch (Exception error)
            {
                MessageBox.Show(error.Message);
            }
            finally
            {
                // Cleanup:
                GC.Collect();
                GC.WaitForPendingFinalizers();
                Marshal.FinalReleaseComObject(ws);
                wb.Close();
                Marshal.FinalReleaseComObject(wb);
                excelApp.Quit();
                Marshal.FinalReleaseComObject(excelApp);
            }

        }

        void fillComboBox(String sql, ComboBox comboBox)
        {
            OleDbCommand cmd = conn.CreateCommand();
            cmd.CommandText = sql;

            OleDbDataReader dr = cmd.ExecuteReader();
            comboBox.Items.Clear();
            while (dr.Read())
            {
                comboBox.Items.Add(dr["name"] + "");
            }
        }

        int fillComboBox4ChepNu(String sql, ComboBox comboBox)
        {
            int count = 0;
            OleDbCommand cmd = conn.CreateCommand();
            cmd.CommandText = sql;

            OleDbDataReader dr = cmd.ExecuteReader();
            comboBox.Items.Clear();
            while (dr.Read())
            {
                comboBox.Items.Add(dr["chepNu"] + "");
                count++;
            }

            return count;
        }

        string makeChengzbh()
        {
            OleDbCommand cmd = conn.CreateCommand();
            cmd.CommandText = "select count(*) from chengzhong where createTime between #" + DateTime.Now.ToString("yyyy-MM-dd") + " 00:00:00# and #" + DateTime.Now.ToString("yyyy-MM-dd") + " 23:59:59#";
            int rtn = (int)cmd.ExecuteScalar();
            return DateTime.Now.ToString("yyyyMMddHHmm") + "_" + this.g_bangfBh + string.Format("_{0:D3}", rtn + 1);
        }

        string getItem(string item)
        {
            if (this.config.AppSettings.Settings[item] == null)
            {
                return string.Empty;
            }
            else
            {
                return this.config.AppSettings.Settings[item].Value;
            }
        }

        // 全局称重编号
        string g_czbh = "";
        string g_bangfBh = "";

        private void form1_Load(object sender, EventArgs e)
        {
            this.Text = "联机称重 Ver " + Assembly.GetExecutingAssembly().GetName().Version.ToString() + " (18610348075 / vx同号)";

            string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Environment.CurrentDirectory + @"\chengzhongku.mdb";
            conn = new OleDbConnection(connectionString);
            try
            {
                conn.Open();
            }
            catch (Exception error)
            {
                MessageBox.Show(error.Message);
                Application.Exit();
                return;
            }

            comboBox_czfs.SelectedIndex = 0;

            ExeConfigurationFileMap ecf = new ExeConfigurationFileMap();
            ecf.ExeConfigFilename = AppDomain.CurrentDomain.BaseDirectory + @"app.config";
            this.config = ConfigurationManager.OpenMappedExeConfiguration(ecf, ConfigurationUserLevel.None);
            this.g_bangfBh = this.getItem("bangfbh");
            label_bfbh.Text = "磅房编号: " + this.g_bangfBh;

            serialPort1.PortName = this.getItem("portName");
            serialPort1.BaudRate = int.Parse(this.getItem("baudRate"));

            label_connectInfo.Text = serialPort1.PortName + ", " + serialPort1.BaudRate;

            try
            {
                serialPort1.Open();
                textBox4.Text = "通讯中...";

            }
            catch (Exception error)
            {
                MessageBox.Show(error.Message);
                Application.Exit();
                return;
            }

            g_czbh = makeChengzbh();
            label1_czbh.Text = "称重编号: " + g_czbh;

            this.serverUrl = this.getItem("serverUrl");

            // 启动的时候自动同步基础数据
            //try
            //{
            //    syncBaseData();
            //}
            //catch (Exception error)
            //{
            //    MessageBox.Show("同步基础数据失败, 检查网络");
            //}

            if (this.getItem("debug").Equals("true"))
            {
                AllocConsole();

                IntPtr stdHandle = CreateFile(
                   "CONOUT$",
                    GENERIC_WRITE,
                    FILE_SHARE_WRITE,
                    0, OPEN_EXISTING, 0, 0
                );

                SafeFileHandle safeFileHandle = new SafeFileHandle(stdHandle, true);
                FileStream fileStream = new FileStream(safeFileHandle, FileAccess.Write);
                
                StreamWriter standardOutput = new StreamWriter(fileStream, Encoding.Default);
                standardOutput.AutoFlush = true;
                Console.SetOut(standardOutput);
            }

            Console.WriteLine("启动成功");
        }

        delegate void SetTextCallback(string text);

        public void SetText(string text)
        {
            if (InvokeRequired)
            {
                var d = new SetTextCallback(SetText);
                this.textBox1.BeginInvoke(d, new object[] { text });
            }
            else
            {
                this.textBox1.Text = text;
            }
        }

        float g_weight = 0F;

        private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            // 防止串口异常关闭时引起读取异常
            if (!serialPort1.IsOpen)
                return;

            // 等待串口数据接收完再读
            Thread.Sleep(500);

            byte[] buffer = new byte[serialPort1.BytesToRead];
            serialPort1.Read(buffer, 0, buffer.Length);

            string str = "";
            foreach(byte b in buffer)
            {
                str += Convert.ToChar(b);
            }

            Console.WriteLine(BitConverter.ToString(buffer));
            Console.WriteLine(str);

            // +00151031D
            if (str.Length > 0)
            {
                try
                {
                    String str2 = str.Substring(2, 6);
                    float weight = float.Parse(str2);
                    weight /= 1000;
                    g_weight = weight;

                    SetText(weight + " 吨");

                } catch(Exception error)
                {
                    Console.WriteLine(error.Message);
                }
            }

        }

        private void form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            Application.Exit();
        }

        bool checkIsDbValue(string tableName, string val)
        {
            OleDbCommand cmd = conn.CreateCommand();
            cmd.CommandText = "select count(*) from " + tableName + " where name = '" + val + "'";

            if ((int)cmd.ExecuteScalar() > 0)
                return true;

            return false;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            OleDbCommand cmd = conn.CreateCommand();

            // 回皮数据要走更新操作
            if (rukhpFlag)
            {
                rukhpFlag = false;
                cmd.CommandText = "update chengzhong set czpizhong = '" + textBox_piz.Text + "', czjingzhong = '" + textBox_jingz.Text +
                    "', updateTime = '" + DateTime.Now.ToString() + "' where czbianhao = '" + g_czbh + "'";

                try
                {
                    if (cmd.ExecuteNonQuery() > 0)
                        MessageBox.Show("更新成功");

                }
                catch (Exception error)
                {
                    MessageBox.Show("异常: " + error.Message, "提示");
                }

                return;
            }
            
            cmd.CommandText = "select count(*) from chengzhong where czbianhao = '" + g_czbh + "'";
            if((int)cmd.ExecuteScalar() > 0)
            {
                MessageBox.Show("称重编号重复，这条记录已经保存了！", "提示");
                return;
            }
           
            if (!checkIsDbValue("cz_wulgs", comboBox_wulgs.Text))
            {
                MessageBox.Show("供应商或项目, 输入的值无效。如需添加新数据，请登录网页版pc管理端后台操作", "提示");
                return;
            }

            if (!checkIsDbValue("cz_wul", comboBox_wul.Text))
            {
                MessageBox.Show("物料, 输入的值无效。如需添加新数据，请登录网页版pc管理端后台操作", "提示");
                return;
            }
            
            if (!checkIsDbValue("cz_guig", comboBox_guig.Text))
            {
                MessageBox.Show("规格, 输入的值无效。如需添加新数据，请登录网页版pc管理端后台操作", "提示");
                return;
            }

            if (!checkIsDbValue("cz_yunsgs", comboBox_yunsgs.Text))
            {
                MessageBox.Show("运输公司, 输入的值无效。如需添加新数据，请登录网页版pc管理端后台操作", "提示");
                return;
            }

            if (textBox_maoz.Text.Equals(""))
            {
                MessageBox.Show("毛重不能为空", "提示");
                return;
            }

            DialogResult dr = MessageBox.Show(this, "请确认出入库标识，选择正确！", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (dr == DialogResult.OK)
            {
                string churkFlag = "";
                if (radioButton_ruk.Checked)
                    churkFlag = "r";
                if (radioButton_chuk.Checked)
                    churkFlag = "c";
                // 其它
                if (radioButton_other.Checked)
                    churkFlag = "q";

                if (textBox_piz.Text.Equals(""))
                    textBox_piz.Text = "0";

                if (textBox_jingz.Text.Equals(""))
                    textBox_jingz.Text = "0";

                cmd.CommandText = "INSERT INTO chengzhong (`czdanwei`, `czpinming`, `czxinghao`, `yunsgsName`, `czchehao`, `czmaozhong`, `czpizhong`, `czjingzhong`, `czrenyuan`, `czfangshi`, `czbianhao`, `czcrku`, `createTime`, `remarks`) " +
                    "VALUES ('" + comboBox_wulgs.Text + "', '" + comboBox_wul.Text + "', '" + comboBox_guig.Text + "', '" + comboBox_yunsgs.Text + "', '" + comboBox_chepNu.Text + "', '" + textBox_maoz.Text + "', '" + textBox_piz.Text + 
                    "', '" + textBox_jingz.Text + "', '" + textBox_chengzy.Text + "','" + comboBox_czfs.Text + "','" + g_czbh + "', '" + churkFlag + "', '" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "', '" + textBox_remark.Text + "')";

                try
                {
                    if (cmd.ExecuteNonQuery() > 0)
                        MessageBox.Show("存盘成功");

                } catch(Exception error)
                {
                    MessageBox.Show("异常: " + error.Message, "提示");
                }

            }
        }

        string getBaseDataFromService(string url, string tableName)
        {
            int success = 0;
            int error = 0;
            OleDbCommand cmd = conn.CreateCommand();
            string rtn = this.httpGet(serverUrl + url);

            SyncObjectDto syncObjectDto = JsonConvert.DeserializeObject<SyncObjectDto>(rtn);
            if (syncObjectDto.success)
            {
                cmd.CommandText = "delete from " + tableName;
                if (cmd.ExecuteNonQuery() >= 0)
                {
                    foreach (string name in syncObjectDto.result)
                    {
                        if (name.Equals(""))
                            continue;

                        cmd.CommandText = "INSERT into " + tableName + "(`name`) values('" + name + "')";
                        if (cmd.ExecuteNonQuery() > 0)
                            success++;
                        else
                            error++;
                    }

                    Console.WriteLine("success: " + success + "; error: " + error);
                }
            }

            return tableName + "，成功：" + success + "; 失败：" + error + "\r\n";
        }

        string getBaseDataFromService4ChengzY(string url, string tableName)
        {
            int success = 0;
            int error = 0;
            OleDbCommand cmd = conn.CreateCommand();
            string rtn = this.httpGet(serverUrl + url);

            SyncObjectDto4ChengzY syncObjectDto = JsonConvert.DeserializeObject<SyncObjectDto4ChengzY>(rtn);
            if (syncObjectDto.success)
            {
                cmd.CommandText = "delete from " + tableName;
                if (cmd.ExecuteNonQuery() >= 0)
                {
                    foreach (UserNamePassword userNamePassword in syncObjectDto.result)
                    {
                        if (userNamePassword == null)
                            continue;

                        cmd.CommandText = "INSERT INTO " + tableName + " (`userName`, `password`) VALUES ('" + userNamePassword.usernmae + "', '" + userNamePassword.password + "')";
                        if (cmd.ExecuteNonQuery() > 0)
                            success++;
                        else
                            error++;
                    }

                    Console.WriteLine("success: " + success + "; error: " + error);
                }
            }

            return tableName + "，成功：" + success + "; 失败：" + error + "\r\n";
        }

        string getBaseDataFromService4Wul(string url, string tableName)
        {
            int success = 0;
            int error = 0;
            OleDbCommand cmd = conn.CreateCommand();
            string rtn = this.httpGet(serverUrl + url);

            SyncObjectDto4Wul syncObjectDto = JsonConvert.DeserializeObject<SyncObjectDto4Wul>(rtn);
            if (syncObjectDto.success)
            {
                cmd.CommandText = "delete from " + tableName;
                if (cmd.ExecuteNonQuery() >= 0)
                {
                    foreach (NameRate nameRate in syncObjectDto.result)
                    {
                        if (nameRate.name == null || nameRate.name.Equals(""))
                            continue;

                        cmd.CommandText = "INSERT INTO " + tableName + " (`name`, `discount`) VALUES ('" + nameRate.name + "', '" + nameRate.rate + "')";
                        if (cmd.ExecuteNonQuery() > 0)
                            success++;
                        else
                            error++;
                    }

                    Console.WriteLine("success: " + success + "; error: " + error);
                }
            }

            return tableName + "，成功：" + success + "; 失败：" + error + "\r\n";
        }

        private void comboBox_wulgs_DropDown(object sender, EventArgs e)
        {
            fillComboBox("select * from cz_wulgs where name like '%" + comboBox_wulgs.Text.Trim() + "%'", comboBox_wulgs);
        }

        private void comboBox_wul_DropDown(object sender, EventArgs e)
        {
            fillComboBox("select * from cz_wul where name like '%" + comboBox_wul.Text.Trim() + "%'", comboBox_wul);
        }

        private void comboBox_guig_DropDown(object sender, EventArgs e)
        {
            fillComboBox("select * from cz_guig where name like '%" + comboBox_guig.Text.Trim() + "%'", comboBox_guig);
        }

        private void comboBox_yunsgs_DropDown(object sender, EventArgs e)
        {
            fillComboBox("select * from cz_yunsgs where name like '%" + comboBox_yunsgs.Text.Trim() + "%'", comboBox_yunsgs);
        }

        void syncBaseData()
        {
            string rtn = getBaseDataFromService("/wulgs/czWulgs/wulgsNameList", "cz_wulgs");
            rtn += getBaseDataFromService4Wul("/wul/czWul/wulNameList", "cz_wul");
            rtn += getBaseDataFromService("/guig/czGuig/guigNameList", "cz_guig");
            rtn += getBaseDataFromService("/yunsgs/czYunsgs/yunsgsNameList", "cz_yunsgs");
            rtn += getBaseDataFromService4ChengzY("/chengzy/czChengzy/chengzyList", "cz_chengzy");

            MessageBox.Show(rtn, "提示");
        }

        private void 同步基础数据ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                syncBaseData();

            } catch(Exception error)
            {
                MessageBox.Show(error.Message);
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            // 测试用
            //textBox_maoz.Text = "14.52";
            //g_weight = 5.58f;
            
            if (g_weight >= 0)
            {
                if (textBox_maoz.Text.Equals(""))
                    textBox_maoz.Text = "0";

                textBox_piz.Text = g_weight + "";
                textBox_jingz.Text = Math.Round((float.Parse(textBox_maoz.Text) - float.Parse(textBox_piz.Text)), 2, MidpointRounding.AwayFromZero) + "";
            }
            else
                MessageBox.Show("没有连接地泵，或者泵上没有车", "提示");

            if (comboBox_chepNu.Text.Equals(""))
            {
                MessageBox.Show("选择或者输入称重车牌号", "提示");
                return;
            }

            if(comboBox_czfs.Text.Equals("自动"))
                textBox_piz.Text = g_weight + "";

            OleDbCommand cmd = conn.CreateCommand();
            cmd.CommandText = "select count(*) from cz_yunscl where chepNu = '" + comboBox_chepNu.Text + "'";
            int rtn = (int)cmd.ExecuteScalar();
            if (rtn > 0)
            {
                DialogResult dr = MessageBox.Show(this, "查询到皮重数据，是否更新？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                if (dr == DialogResult.OK)
                {
                    cmd.CommandText = "update cz_yunscl set piz = '" + textBox_piz.Text + "' where chepNu = '" + comboBox_chepNu.Text + "'";
                    if(cmd.ExecuteNonQuery() > 0)
                        MessageBox.Show("操作成功", "提示");
                    else
                        MessageBox.Show("操作失败", "提示");
                }
                else
                {
                    ;
                }

            } else
            {
                DialogResult dr = MessageBox.Show(this, "是否保存皮重？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                if (dr == DialogResult.OK)
                {
                    cmd.CommandText = "insert into cz_yunscl (`chepNu`, `piz`) values ('" + comboBox_chepNu.Text + "', " + g_weight + ")";
                    if (cmd.ExecuteNonQuery() > 0)
                        MessageBox.Show("操作成功", "提示");
                    else
                        MessageBox.Show("操作失败", "提示");
                }
                else
                {
                    ;
                }
            }

            

        }

        private void button4_Click(object sender, EventArgs e)
        {
            if(comboBox_chepNu.Text.Equals(""))
            {
                MessageBox.Show("请选择或者输入车号", "提示");
                return;
            }

            if (g_weight != 0)
            {
                textBox_maoz.Text = Math.Round(g_weight * (1 + g_wulDiscount), 2, MidpointRounding.AwayFromZero) + "";
                if (!textBox_piz.Text.Equals(""))
                {
                    double temp = Math.Round(float.Parse(textBox_maoz.Text) - float.Parse(textBox_piz.Text), 2, MidpointRounding.AwayFromZero);
                    textBox_jingz.Text = temp + "";
                }
            }
            else
                MessageBox.Show("没有连接地泵，或者泵上没有车", "提示");
        }

        private void textBox_maoz_KeyPress(object sender, KeyPressEventArgs e)
        {
            //如果输入的不是退格和数字和"."，则屏蔽输入
            if (!(e.KeyChar == '.' || e.KeyChar == '\b' || (e.KeyChar >= '0' && e.KeyChar <= '9')))
            {
                e.Handled = true;
            }

            
        }

        private void textBox_piz_KeyPress(object sender, KeyPressEventArgs e)
        {
            //如果输入的不是退格和数字和"."，则屏蔽输入
            if (!(e.KeyChar == '.' || e.KeyChar == '\b' || (e.KeyChar >= '0' && e.KeyChar <= '9')))
            {
                e.Handled = true;
            }

            
        }

        private void textBox_jingz_KeyPress(object sender, KeyPressEventArgs e)
        {
            //如果输入的不是退格和数字和"."，则屏蔽输入
            if (!(e.KeyChar == '.' || e.KeyChar == '\b' || (e.KeyChar >= '0' && e.KeyChar <= '9')))
            {
                e.Handled = true;
            }
        }

        private void comboBox_czfs_SelectedIndexChanged(object sender, EventArgs e)
        {
            if(comboBox_czfs.Text.Equals("自动"))
            {
                textBox_piz.Enabled = false;
                textBox_maoz.Enabled = false;
                textBox_jingz.Enabled = false;

                //textBox_piz.Text = "";
                //textBox_maoz.Text = "";
                //textBox_jingz.Text = "";
                //comboBox_chepNu.Text = "";
                textBox_czsj.Enabled = false;

            } else
            {
                textBox_piz.Enabled = true;
                textBox_maoz.Enabled = true;
                textBox_jingz.Enabled = true;
                textBox_czsj.Enabled = true;
            }
        }

        private void comboBox_chepNu_DropDown(object sender, EventArgs e)
        {
            //fillComboBox4ChepNu("select * from cz_yunscl where chepNu like '%" + comboBox_chepNu.Text.Trim() + "%'", comboBox_chepNu);
            fillComboBox4ChepNu("select * from cz_yunscl", comboBox_chepNu);
        }

        private void comboBox_chepNu_SelectedIndexChanged(object sender, EventArgs e)
        {
            OleDbCommand cmd = conn.CreateCommand();
            cmd.CommandText = "select * from cz_yunscl where chepNu = '" + comboBox_chepNu.Text + "'";
            OleDbDataReader dr = cmd.ExecuteReader();
            if (dr.Read())
            {
                float temp = float.Parse(dr["piz"] + "");
                textBox_piz.Text = Math.Round(temp, 2, MidpointRounding.AwayFromZero) + "";
            }

        }

        private void button6_Click(object sender, EventArgs e)
        {
            g_czbh = makeChengzbh();
            label1_czbh.Text = "称重编号: " + g_czbh;

            comboBox_czfs.SelectedIndex = 0;

            //comboBox_wulgs.Text = "";
            //comboBox_wul.Text = "";
            //comboBox_guig.Text = "";
            //comboBox_yunsgs.Text = "";
            comboBox_chepNu.Text = "";

            textBox_maoz.Text = "";
            textBox_piz.Text = "";
            textBox_jingz.Text = "";

            //radioButton_ruk.Checked = true;

            textBox_remark.Text = "";
            textBox_czsj.Text = "";

            // 补打称重单
            budczd = null;
        }

        private void comboBox_wulgs_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Space)
            {
                (sender as ComboBox).DroppedDown = true;
            }
        }

        bool rukhpFlag = false;
        private void button7_Click(object sender, EventArgs e)
        {
            rukhpFlag = true;
            rukhp form2 = new rukhp(0);
            form2.MyEvent += new MyDelegate(form2_MyEvent);

            form2.ShowDialog();

        }

        String budczd = null;
        private void form2_MyEvent(ChengzDataDto chengzDataDto)
        {
            g_czbh = chengzDataDto.称重编号;
            label1_czbh.Text = "称重编号: " + g_czbh;

            comboBox_wulgs.Text = chengzDataDto.供应商或项目;
            comboBox_wul.Text = chengzDataDto.物料;
            comboBox_guig.Text = chengzDataDto.规格;
            comboBox_yunsgs.Text = chengzDataDto.运输公司;
            comboBox_chepNu.Text = chengzDataDto.运输车辆;
            textBox_maoz.Text = chengzDataDto.毛重;
            textBox_piz.Text = chengzDataDto.皮重;
            textBox_jingz.Text = chengzDataDto.净重;
            comboBox_czfs.Text = chengzDataDto.称重方式;

            if (chengzDataDto.出入库标记.Equals("r"))
                radioButton_ruk.Checked = true;
            if (chengzDataDto.出入库标记.Equals("c"))
                radioButton_chuk.Checked = true;
            if (chengzDataDto.出入库标记.Equals("q"))
                radioButton_other.Checked = true;

            textBox_remark.Text = chengzDataDto.备注;
            textBox_czsj.Text = chengzDataDto.称重时间;
            budczd = chengzDataDto.类型;
        }

        private void button8_Click(object sender, EventArgs e)
        {
            rukhp form2 = new rukhp(1);
            form2.MyEvent += new MyDelegate(form2_MyEvent);

            form2.ShowDialog();

        }

        private void 上传磅单ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            new SyncBangD().ShowDialog();
        }

        private void comboBox_wul_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Space)
            {
                (sender as ComboBox).DroppedDown = true;
            }
        }

        private void comboBox_guig_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Space)
            {
                (sender as ComboBox).DroppedDown = true;
            }
        }

        private void comboBox_yunsgs_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Space)
            {
                (sender as ComboBox).DroppedDown = true;
            }
        }

        private void comboBox_chepNu_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                int rtn = fillComboBox4ChepNu("select * from cz_yunscl where chepNu like '%" + comboBox_chepNu.Text.Trim() + "%'", comboBox_chepNu);
                //(sender as ComboBox).DroppedDown = true;

                if (rtn > 0)
                {
                    comboBox_chepNu.SelectedIndex = 0;
                    comboBox_chepNu.Select(comboBox_chepNu.Text.Length, 0);
                }
            }
        }

        double g_wulDiscount = 0;
        private void comboBox_wul_SelectedIndexChanged(object sender, EventArgs e)
        {
            OleDbCommand cmd = conn.CreateCommand();
            cmd.CommandText = "select * from cz_wul where name = '" + comboBox_wul.Text + "'";
            OleDbDataReader dr = cmd.ExecuteReader();
            if (dr.Read())
            {
                g_wulDiscount = double.Parse(dr["discount"] + "") / 100;
                g_wulDiscount = Math.Round(g_wulDiscount, 2, MidpointRounding.AwayFromZero);
                
                //label_maoz.Text = "毛重(" + g_wulDiscount + ")";
            }
        }

        private void 车号管理ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            new yunscl().ShowDialog();
        }

        Image image = null;
        private void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
        {
            e.Graphics.DrawImage(image, new Rectangle(10, 10, this.image.Width, this.image.Height));
        }

        private void textBox_piz_KeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                double temp = Math.Round(float.Parse(textBox_maoz.Text) - float.Parse(textBox_piz.Text), 2, MidpointRounding.AwayFromZero);
                textBox_jingz.Text = temp + "";

            }
            catch (Exception error)
            {
                Console.WriteLine(error.Message);
            }
        }

        private void textBox_maoz_KeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                double temp = Math.Round(float.Parse(textBox_maoz.Text) - float.Parse(textBox_piz.Text), 2, MidpointRounding.AwayFromZero);
                textBox_jingz.Text = temp + "";

            }
            catch (Exception error)
            {
                Console.WriteLine(error.Message);
            }
        }
    }
}
